﻿using Spring.Context;
using Spring.Context.Support;
using System;
using System.Windows.Forms;
using Wise.TimeWarrior.Properties;
using Wise.TimeWarrior.Business;
using Wise.TimeWarrior.DTO;

namespace Wise.TimeWarrior
{
    /// <summary>
    /// Main Class
    /// </summary>
    public class TimeWarriorTryApp : Form
    {
        /// <summary>
        /// Function starting 
        /// </summary>
        [STAThread]
        public static void Main()
        {
            Application.Run(new TimeWarriorTryApp());
        }

        private NotifyIcon trayIcon;
        private ContextMenu trayMenu;
        private IApplicationLogic applicationLogic;
        private IApplicationContext ctx;
        /// <summary>
        /// .ctor
        /// </summary>
        public TimeWarriorTryApp()
        {
            SetupSpringContext();
            
            trayMenu = new ContextMenu();

            foreach (BusinessItemDto i in applicationLogic.GetAllLogics())
            {
                trayMenu.MenuItems.Add(string.IsNullOrEmpty(i.TranslatedActionName) ? i.OriginalMethodName : i.TranslatedActionName, new EventHandler((e, p) => i.Action.Invoke()));
            }

            trayIcon = new NotifyIcon();
            trayIcon.Text = Resources.TRYAPP_TRAYICON_TEXT;
            trayIcon.Icon = Resources.favicon;
            trayIcon.ContextMenu = trayMenu;
            trayIcon.Visible = true;
        }




        private void SetupSpringContext()
        {
            ctx = ContextRegistry.GetContext();

            applicationLogic = ctx.GetObject("applicationLogic") as IApplicationLogic;
            if (applicationLogic != null)
            {
                applicationLogic.SetupLogic();
            }
            else
            {
                throw new NullReferenceException("applicationLogic");
            }
        }


        /// <summary>
        /// <see cref="Form.OnLoad"/>
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            Visible = false; // Hide form window.
            ShowInTaskbar = false; // Remove from taskbar.
            base.OnLoad(e);
        }

        /// <summary>
        /// <see cref="IDisposable.Dispose"/>
        /// </summary>
        protected override void Dispose(bool isDisposing)
        {
            if (isDisposing)
            {
                // Release the icon resource.
                trayIcon.Dispose();
                applicationLogic.Dispose();
            }

            base.Dispose(isDisposing);
        }
    }
}